package com.osce.web.controller.system;

import com.osce.common.annotation.Excel;
import com.osce.common.annotation.Log;
import com.osce.common.core.controller.BaseController;
import com.osce.common.core.entity.AjaxResult;
import com.osce.common.core.entity.TreeSelect;
import com.osce.common.core.entity.dto.req.SysDeptReq;
import com.osce.common.core.entity.entity.SysRole;
import com.osce.common.core.entity.entity.SysUser;
import com.osce.common.core.page.TableDataInfo;
import com.osce.common.enums.BusinessType;
import com.osce.common.utils.SecurityUtils;
import com.osce.common.utils.StringUtils;
import com.osce.common.utils.poi.ExcelUtil;
import com.osce.interfaces.system.ISysDeptService;
import com.osce.interfaces.system.ISysPostService;
import com.osce.interfaces.system.ISysRoleService;
import com.osce.interfaces.system.ISysUserService;
import jxl.Sheet;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Slf4j
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysPostService postService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user, String exportFields, String encryptFields) {
        List<SysUser> list = userService.selectUserList(user);

        // 导出记录数量限制，最多5000条
        if (list.size() > 5000) {
            throw new RuntimeException("导出数据过多，请添加查询条件限制导出范围（最大导出5000条）");
        }

        // 根据前端传递的加密字段列表进行脱敏处理
        Set<String> fieldsToEncrypt = new HashSet<>();
        if (StringUtils.isNotEmpty(encryptFields)) {
            fieldsToEncrypt = new HashSet<>(Arrays.asList(encryptFields.split(",")));
        }

        // 对指定字段进行脱敏处理
        for (SysUser sysUser : list) {
            // 对身份证号进行脱敏
            if (fieldsToEncrypt.contains("identity") && StringUtils.isNotEmpty(sysUser.getIdentity())) {
                sysUser.setIdentity(desensitizeIdentity(sysUser.getIdentity()));
            }
            // 对手机号进行脱敏
            if (fieldsToEncrypt.contains("phonenumber") && StringUtils.isNotEmpty(sysUser.getPhonenumber())) {
                sysUser.setPhonenumber(desensitizePhone(sysUser.getPhonenumber()));
            }
        }

        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);

        // 如果指定了导出字段，计算需要排除的字段
        if (StringUtils.isNotEmpty(exportFields)) {
            Set<String> selectedFields = new HashSet<>(Arrays.asList(exportFields.split(",")));
            List<String> excludeFields = new ArrayList<>();

            // 定义直接在SysUser类中的字段
            if (!selectedFields.contains("userName")) excludeFields.add("userName");
            if (!selectedFields.contains("nickName")) excludeFields.add("nickName");
            if (!selectedFields.contains("email")) excludeFields.add("email");
            if (!selectedFields.contains("identity")) excludeFields.add("identity");
            if (!selectedFields.contains("phonenumber")) excludeFields.add("phonenumber");
            if (!selectedFields.contains("birthday")) excludeFields.add("birthday");
            if (!selectedFields.contains("sex")) excludeFields.add("sex");
            if (!selectedFields.contains("status")) excludeFields.add("status");
            if (!selectedFields.contains("loginIp")) excludeFields.add("loginIp");
            if (!selectedFields.contains("loginDate")) excludeFields.add("loginDate");

            // 特殊处理嵌套对象的字段，deptName是通过dept对象关联的
            if (!selectedFields.contains("deptName")) excludeFields.add("dept.deptName");

            // 注意：school、base、post字段在SysUserInfo类中，当前ExcelUtil无法直接处理跨实体的字段排除
            // 这些字段需要在数据查询或转换时进行处理

            // 调用hideColumn方法排除不需要的字段
            if (!excludeFields.isEmpty()) {
                util.hideColumn(excludeFields.toArray(new String[0]));
            }
        }
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 对身份证号进行脱敏处理
     * 保留前4位和后4位，中间用*号代替
     * @param identity 身份证号
     * @return 脱敏后的身份证号
     */
    private String desensitizeIdentity(String identity) {
        if (StringUtils.isEmpty(identity) || identity.length() < 8) {
            return identity;
        }
        StringBuilder sb = new StringBuilder();
        // 保留前4位
        sb.append(identity.substring(0, 4));
        // 中间用*代替
        for (int i = 0; i < identity.length() - 8; i++) {
            sb.append('*');
        }
        // 保留后4位
        sb.append(identity.substring(identity.length() - 4));
        return sb.toString();
    }

    /**
     * 对手机号进行脱敏处理
     * 保留前3位和后4位，中间用*号代替
     * @param phone 手机号
     * @return 脱敏后的手机号
     */
    private String desensitizePhone(String phone) {
        if (StringUtils.isEmpty(phone) || phone.length() < 7) {
            return phone;
        }
        StringBuilder sb = new StringBuilder();
        // 保留前3位
        sb.append(phone.substring(0, 3));
        // 中间用*代替（通常手机号为11位，中间4位用*代替）
        int maskLength = Math.min(4, phone.length() - 7);
        for (int i = 0; i < maskLength; i++) {
            sb.append('*');
        }
        // 保留后4位
        sb.append(phone.substring(phone.length() - 4));
        return sb.toString();
    }




    /**
     * 导入用户数据
     */
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) {
        try {
            ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
            List<SysUser> userList = util.importExcel(file.getInputStream());
            String operName = getUsername();

            // 调用service层导入数据，此时即使部分数据失败，也会继续处理并返回完整结果
            String message = userService.importUser(userList, updateSupport, operName);

            // 返回成功消息，包含导入结果详情
            return AjaxResult.success(message);
        } catch (Exception e) {
            // 捕获解析文件等非业务异常
            log.error("导入用户数据失败：{}", e.getMessage(), e);
            return AjaxResult.error("导入用户数据失败：" + e.getMessage());
        }
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        try {
            // 创建Excel工具类
            ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);

            // 查询所有组织结构
            SysDeptReq deptReq = new SysDeptReq();
            List<TreeSelect> deptTreeList = deptService.selectDeptTreeList(deptReq);

            // 创建一个示例用户对象，用于在模板中展示科室ID和名称的对应关系
            List<SysUser> userList = new ArrayList<>();

            // 创建一个注释行，说明科室ID的使用方法
            SysUser headerComment = new SysUser();
            headerComment.getDept().setDeptName("请输入正确的科室ID，下方列出可选的科室信息");
            userList.add(headerComment);

            // 添加科室信息到用户列表中，通过不同字段展示ID和名称对应关系
            addDeptToUserList(userList, deptTreeList, 0);

            // 初始化Excel模板，包含科室信息
            util.init(userList, "用户数据", "用户导入模板", Excel.Type.IMPORT);

            // 导出Excel模板
            util.exportExcel(response);
        } catch (Exception e) {
            log.error("生成用户导入模板失败", e);
            // 如果出错，使用默认方法
            ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
            util.importTemplateExcel(response, "用户数据");
        }
    }

    /**
     * 递归添加科室信息到用户列表中
     */
    private void addDeptToUserList(List<SysUser> userList, List<TreeSelect> deptTreeList, int level) {
        if (deptTreeList == null || deptTreeList.isEmpty()) {
            return;
        }

        String indent = "";
        for (int i = 0; i < level; i++) {
            indent += "  - ";
        }

        for (TreeSelect dept : deptTreeList) {
            SysUser deptUser = new SysUser();
            // 在用户ID字段中展示科室ID
            deptUser.setUserId(dept.getId());
            // 在部门名称字段中展示科室名称，并添加缩进以显示层级关系
            deptUser.getDept().setDeptName(indent + dept.getLabel());
            userList.add(deptUser);

            // 递归处理子科室
            if (dept.getChildren() != null && !dept.getChildren().isEmpty()) {
                addDeptToUserList(userList, dept.getChildren(), level + 1);
            }
        }
    }

    /**
     * 递归收集所有科室ID
     */
    private void collectDeptIds(List<TreeSelect> deptTreeList, List<String> deptIds) {
        if (deptTreeList == null || deptTreeList.isEmpty()) {
            return;
        }
        for (TreeSelect dept : deptTreeList) {
            deptIds.add(dept.getId().toString());
            if (dept.getChildren() != null && !dept.getChildren().isEmpty()) {
                collectDeptIds(dept.getChildren(), deptIds);
            }
        }
    }

    /**
     * 递归添加科室信息到提示文本
     */
    private void appendDeptInfo(StringBuilder prompt, List<TreeSelect> deptTreeList, int level) {
        if (deptTreeList == null || deptTreeList.isEmpty()) {
            return;
        }

        String indent = "";
        for (int i = 0; i < level; i++) {
            indent += "  - ";
        }

        for (TreeSelect dept : deptTreeList) {
            prompt.append(indent).append("科室ID: ").append(dept.getId())
                  .append("  科室名称: " + dept.getLabel()).append("\n");
            if (dept.getChildren() != null && !dept.getChildren().isEmpty()) {
                appendDeptInfo(prompt, dept.getChildren(), level + 1);
            }
        }
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        SysRole sysRole = new SysRole();
        sysRole.setCreateBy(getUsername());
        List<SysRole> roles = roleService.selectRoleAll(sysRole);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 恢复用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "恢复用户", businessType = BusinessType.UPDATE)
    @GetMapping("/recover/{userId}")
    public AjaxResult recoverUser(@PathVariable Long userId) {
        return toAjax(userService.recoverUser(userId));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId, user.getCreateBy());
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取科室树列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept_tree:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDeptReq dept) {
        return success(deptService.selectDeptTreeList(dept));
    }
}
